import tkinter as tk
from shared import SharedData
import ui_utils
import file_operations
import model_operations
import data_operations
import train_operations
import infer_operations
import about_operations
from tkinter import messagebox
from client_socket import ClientSocket
from predict_operations import YOLOPredictor
import os
class AIApplication(tk.Tk):
    def __init__(self):
        super().__init__()
        self.shared_data = SharedData()
        self.shared_data.ui_elements["app"] = self
        self.client_socket = ClientSocket()

        # === 新增：初始化 YOLO 预测器 ===
        # 将 os.path.dirname() 嵌套三次，从 mainpage.py -> yolo_front -> Project2 -> ultralytics
        # 模型路径
        model_path = os.path.abspath(
            os.path.join(
                os.path.dirname(__file__), "..", "results", "result111", "train","weights", "best.pt"
            )
        )
        if not os.path.exists(model_path):
            messagebox.showerror("错误", f"未找到模型文件：\n{model_path}\n请确认路径正确。")
            return
        self.predictor = YOLOPredictor(model_path=model_path)
        

        # 设置窗口基本属性
        self.title("yolo")
        self.geometry("1200x680")
        self.minsize(800, 500)

        # 初始化界面
        ui_utils.setup_styles(self)
        ui_utils.create_menu(self, self.shared_data)
        ui_utils.create_main_interface(self, self.shared_data)



        # 绑定事件
        file_operations.bind_menu_events(self)

        # 加载最近文件
        file_operations.load_recent_files(self.shared_data)
        file_operations.update_recent_files_menu(self.shared_data, self)

        # 绑定快捷键
        self.bind("<Control-o>", lambda e: self.cmd_open_image())
        self.bind("<Control-v>", lambda e: self.cmd_open_video())
        self.bind("<Control-c>", lambda e: self.cmd_open_camera())
        self.bind("<Control-q>", lambda e: self.quit_application())

        # 推理菜单的快捷键绑定
        # 绑定快捷键
        # self.bind('<Alt-5>', lambda event: self.cmd_infer_start())
        self.bind("<Control-d>", lambda e: self.cmd_infer_start())
        self.bind("<Control-p>", lambda e: self.cmd_infer_pause())
        self.bind("<Control-i>", lambda e: self.cmd_infer_stop())

    # 文件菜单相关方法
    def on_menu_motion(self, event):
        file_operations.on_menu_motion(self, event)

    def on_submenu_leave(self, event):
        file_operations.on_submenu_leave(self, event)

    def on_window_click(self, event):
        file_operations.on_window_click(self, event)

    def cmd_open_folder(self):
        file_operations.cmd_open_folder(self.shared_data, self)

    def cmd_open_image(self):
        file_operations.cmd_open_image(self.shared_data, self)

    def cmd_open_video(self):
        file_operations.cmd_open_video(self.shared_data, self)

    def cmd_open_camera(self):
        file_operations.cmd_open_camera(self.shared_data, self)

    def cmd_save_result(self):
        file_operations.cmd_save_result(self.shared_data, self)

    def cmd_batch_detect(self):
        file_operations.cmd_batch_detect(self.shared_data, self)
    
    def cmd_delete_selected_file(self):
        """菜单命令：删除文件列表中选中的项"""
        file_listbox = self.shared_data.ui_elements.get("file_listbox")
        if not file_listbox or not file_listbox.curselection():
            messagebox.showinfo("提示", "请先在文件列表中选择一个项目。")
            return
        # 调用已有的删除函数
        file_operations.on_file_delete(self.shared_data, self, None)

    def quit_application(self, event=None):
        file_operations.quit_application(self.shared_data, self, event)
    
    def stop_camera_and_hide_button(self):
        file_operations.stop_camera_and_hide_button(self.shared_data, self)

    def toggle_video_play(self, event=None):
        file_operations.toggle_video_play(self.shared_data, self)


    # 模型菜单相关方法
    def update_scale_label(self, value, label):
        model_operations.update_scale_label(self, value, label, self.shared_data)

    def on_model_version_change(self, event):
        model_operations.on_model_version_change(self, event, self.shared_data)

    def on_model_weight_change(self, event):
        model_operations.on_model_weight_change(self, event, self.shared_data)

    def cmd_load_model(self):
        model_operations.cmd_load_model(self.shared_data, self)

    def cmd_model_library(self):
        model_operations.cmd_model_library(self.shared_data, self)

    def cmd_model_params(self):
        model_operations.cmd_model_params(self.shared_data, self)

    # 数据菜单相关方法
    def cmd_load_data(self):
        data_operations.cmd_load_data(self,app)

    # 训练菜单相关方法
    def cmd_train_params(self):
        train_operations.cmd_train_params(self)

    def cmd_train_start(self):
        train_operations.cmd_train_start(self)

    def cmd_train_pause(self):
        train_operations.cmd_train_pause(self)

    def cmd_train_stop(self):
        train_operations.cmd_train_stop(self)

    # 推理菜单相关方法
    def on_pred_file_select(self, event):
        infer_operations.on_pred_file_select(self.shared_data, self, event)

    def on_pred_key_up(self, event):
        infer_operations.on_pred_key_up(self.shared_data, self, event)

    def on_pred_key_down(self, event):
        infer_operations.on_pred_key_down(self.shared_data, self, event)

    def cmd_infer_params(self):
        infer_operations.cmd_infer_params(self)

    def cmd_infer_start(self):
        infer_operations.cmd_infer_start(self.shared_data, self)

    def cmd_infer_pause(self):
        infer_operations.cmd_infer_pause(self)

    def cmd_infer_stop(self):
        infer_operations.cmd_infer_stop(self)

    # 关于菜单相关方法
    def cmd_about(self):
        about_operations.cmd_about(self)

    def cmd_help(self):
        about_operations.cmd_help(self)

    # 文件列表相关方法
    def on_file_select(self, event):
        file_operations.on_file_select(self.shared_data, self, event)

    def on_key_up(self, event):
        file_operations.on_key_up(self.shared_data, self, event)

    def on_key_down(self, event):
        file_operations.on_key_down(self.shared_data, self, event)

    # 界面相关方法
    def update_source_placeholder_position(self, event=None):
        """动态更新源文件展示区域占位文字位置"""
        source_canvas = self.shared_data.ui_elements["source_canvas"]
        if source_canvas.find_withtag("placeholder"):
            width = source_canvas.winfo_width()
            height = source_canvas.winfo_height()
            source_canvas.coords("placeholder", width // 2, height // 2)

    def update_result_placeholder_position(self, event=None):
        """动态更新预测结果展示区域占位文字位置"""
        result_canvas = self.shared_data.ui_elements["result_canvas"]
        if result_canvas.find_withtag("placeholder"):
            width = result_canvas.winfo_width()
            height = result_canvas.winfo_height()
            result_canvas.coords("placeholder", width // 2, height // 2)

    def show_status(self, message):
        """显示状态信息"""
        print(f"操作: {message}")
        # 可以在这里添加状态栏显示逻辑


if __name__ == "__main__":
    app = AIApplication()
    app.mainloop()